package com.ruoyi.controller.jpjs.municipal;

import com.ruoyi.common.constant.MsgConstants;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.jpjs.common.municipal.Income;
import com.ruoyi.domain.jpjs.common.municipal.IncomeDetail;
import com.ruoyi.domain.jpjs.common.municipal.IncomeParam;
import com.ruoyi.domain.jpjs.common.municipal.Payment;
import com.ruoyi.domain.jpjs.common.municipal.expend.Team;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.service.jpjs.municipal.IncomeService;
import com.ruoyi.system.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.*;

import static org.apache.cxf.rs.security.oauth2.tokens.mac.HmacAlgorithm.HmacSHA256;

/**
 * 市政收入 控制层
 */
@SuppressWarnings("ALL")
@Controller
@RequestMapping("/income")
public class IncomeController extends BaseController {

    private String prefix = "jpjs/municipal/income";

    private String team_prefix = "jpjs/municipal/cost";

    @Autowired
    private IncomeService incomeService;

    /**
     * 首页面
     */
    @GetMapping()
    public String view(ModelMap mmp) {
        return prefix + "/list";
    }

    /**
     * 首页面 -> 初始化数据
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(Income income) {
        startPage();
        income.setProgramName(income.getProgramName().trim().replaceAll(",", ""));

        // 获取当前的用户信息
        SysUser sysUser = ShiroUtils.getSysUser();
        // 获取当前的用户ID
        Long userId = sysUser.getUserId();

        income.setUserId(userId);
        // 获取当前登录人对应的项目权限
        List<Income> incomes = incomeService.queryIncomeList(income);
        if(StringUtils.isNotEmpty(incomes)){
            incomeService.deletePayment();
            for(Income incomeObj : incomes){
                // 截止上月累计产值
                List<Income> incomeList = incomeService.queryIncomeListForCount(incomeObj);
                Double actualFinish = 0.00;
                if(StringUtils.isNotEmpty(incomeList)){
                    for (Income incomeOb : incomeList){
                        Double actualFinishValue = Double.valueOf(incomeOb.getActualFinish().replace(".00", ""));
                        actualFinish = actualFinish + actualFinishValue;
                    }
                }
                // 截止当月累计回款
                List<Income> incomeLists = incomeService.queryIncomeListForPay(incomeObj);
                Double pay = 0.00;
                if(StringUtils.isNotEmpty(incomeLists)){
                    for (Income incomeOb : incomeLists){
                        Double actualPayment = Double.valueOf(incomeOb.getActualPayment().replace(".00", ""));
                        pay = pay + actualPayment;
                    }
                }

                Payment payment = new Payment();
                payment.setCompanyId(incomeObj.getCompanyId());
                payment.setProgramId(incomeObj.getProgramId());
                payment.setActualMonth(incomeObj.getActualMonth());
                payment.setAcIncome(actualFinish);
                payment.setAcPayment(pay);
                incomeService.insertPayment(payment);
            }
        }


        return getDataTable(incomes);
    }

    /**
     * 首页面 -> 批量删除
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(incomeService.deleteIncomeById(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 首页面 -> 详情
     */
    @GetMapping("/detail")
    public String detail(ModelMap mmp, String programId,String actualMonth) {
        Map<String, Object> map = new HashMap<>();
        map.put("programId", programId);
        map.put("actualMonth", actualMonth);
        // 产值明细信息
        List<IncomeDetail> incomeDetails = incomeService.queryIncomeDetailMonth(map);

        mmp.put("incomeDetails", incomeDetails);
        return prefix + "/details";
    }

    /**
     * 首页面 -> 导出
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(Income income) {
        income.setProgramName(income.getProgramName().trim().replaceAll(",", ""));
        // 获取当前的用户信息
        SysUser sysUser = ShiroUtils.getSysUser();
        income.setUserId(sysUser.getUserId());

        List<Income> list = incomeService.queryIncomeList(income);
        ExcelUtil<Income> util = new ExcelUtil<Income>(Income.class);
        return util.exportExcel(list, "产值运营表");
    }

    /**
     * 新增页面
     */
    @GetMapping("/addView")
    public String addView(ModelMap mmp, String programName, String companyId, String programId) {
        Map<String, Object> map = new HashMap<>();
        mmp.put("companyId", companyId);
        mmp.put("programId", programId);
        mmp.put("programName", programName);
        return prefix + "/add";
    }

    /**
     * 新增页面 -> 保存
     */
    @PostMapping("/save")
    @ResponseBody
    public AjaxResult save(IncomeParam incomeParam) {
        // Step1 校验 同一个项目下的计划月份、实际月份唯一性
        if (MsgConstants.MONTH_NOT_UNIQUE.equals(incomeService.checkMonthUnique(incomeParam))) {
            return error("新增产值,存在重复月份!");
        }

        // Step2 新增产值表
        incomeParam.setCreater(ShiroUtils.getSysUser().getUserName());
        incomeService.addIncome(incomeParam);
        int incomeId = incomeParam.getIncomeId();

        // Step3 新增产值明细表
        List<IncomeDetail> incomeDetails = incomeParam.getIncomeDetail();
        // tip:会多出一个null的数据,需要删除集合中某一元素值
        incomeDetails.stream().findFirst().map(vo -> {
            if (StringUtils.isEmpty(vo.getActualMonth())) {
                incomeDetails.remove(vo);
            }
            return vo;
        });

        if (StringUtils.isNotEmpty(incomeDetails)) {
            for (IncomeDetail incomeDetail : incomeDetails) {
                incomeDetail.setIncomeId(incomeId);
                incomeDetail.setProgramId(incomeParam.getProgramId());
                incomeDetail.setActualMonth(incomeParam.getActualMonth());
                incomeDetail.setPlanMonth(incomeParam.getPlanMonth());
            }
        }
        return toAjax(incomeService.addIncomeDetail(incomeDetails));
    }

    /**
     * 更新页面
     */
    @GetMapping("/editView")
    public String editView(ModelMap mmp, String incomeId) {
        Map<String, Object> map = new HashMap<>();
        map.put("incomeId", incomeId);
        // 产值信息
        List<Income> incomes = incomeService.queryIncomeObj(map);
        // 产值明细信息
        List<IncomeDetail> incomeDetails = incomeService.queryIncomeDetail(map);
        mmp.put("income", incomes.get(0));
        mmp.put("incomeDetails", incomeDetails);
        return prefix + "/edit";
    }

    /**
     * 更新页面 -> 编辑
     */
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult edit(IncomeParam incomeParam) {
        // Step1 校验 计划月份、实际月份唯一性
        if (MsgConstants.MONTH_NOT_UNIQUE.equals(incomeService.checkMonthUniqueEdit(incomeParam))) {
            return error("更新产值,存在重复月份!");
        }

        // Step2 新增产值表
        incomeService.updateIncome(incomeParam);

        // Step3 新增产值明细表
        incomeService.deleteIncomeDetail(incomeParam);

        List<IncomeDetail> incomeDetails = incomeParam.getIncomeDetail();
        if (StringUtils.isNotEmpty(incomeDetails)) {
            for (IncomeDetail incomeDetail : incomeDetails) {
                incomeDetail.setIncomeId(incomeParam.getIncomeId());
                incomeDetail.setActualMonth(incomeParam.getActualMonth());
                incomeDetail.setPlanMonth(incomeParam.getPlanMonth());
                incomeDetail.setProgramId(incomeParam.getProgramId());
            }
        }
        return toAjax(incomeService.addIncomeDetail(incomeDetails));
    }



}
